//
//  XcodeCleanItemV.swift
//  ZJTools
//
//  Created by 万孟超 on 2023/11/17.
//

import Cocoa
import SnapKit

struct XcodeCleanItemM {
    var title: String
    
    var action: (() -> ())
    
}

class XcodeCleanItemV: NSView {
    var itemArray: [XcodeCleanItemM]
    
    var viewArray: [XcodeCleanItem] = []
    
    var maskView: NSView = {
       let mask = NSView()
        mask.wantsLayer = true
        mask.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.4).cgColor
        mask.layer?.cornerRadius = 10
        return mask
    }()
    
    init(itemArray: [XcodeCleanItemM]) {
        self.itemArray = itemArray
        super.init(frame: .zero)
        installSubView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func freshItemSize(_ index: Int, size: Double) {
        viewArray[index].refreshSize(size)
    }
    
    func installSubView() {
        
        addSubview(maskView)
        maskView.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.right.equalTo(10)
            make.height.equalTo(80)
            make.top.equalToSuperview()
        }
        
        for (idx, item) in itemArray.enumerated() {
            let view = XcodeCleanItem()
            view.itemModel = item
            view.selectAction = { [weak self] in
                guard let self = self else { return }
                NSAnimationContext.runAnimationGroup { context in
                    context.duration = 0.1
                    context.timingFunction = CAMediaTimingFunction(name: .linear)
                    context.allowsImplicitAnimation = true
                    self.maskView.snp.updateConstraints { make in
                        make.top.equalTo(idx * 80)
                    }
                    self.layoutSubtreeIfNeeded()
                }
            }
            addSubview(view)
            view.snp.makeConstraints { make in
                make.left.equalTo(35)
                make.right.equalTo(-20)
                make.height.equalTo(80)
                if let lastView = viewArray.last {
                    make.top.equalTo(lastView.snp.bottom)
                }else{
                    make.top.equalToSuperview()
                }
                if idx == itemArray.count - 1 {
                    make.bottom.equalToSuperview()
                }
            }
            viewArray.append(view)
        }
    }
}
